import React, { useEffect, useState, useMemo } from 'react'
import { useLocation, Navigate } from 'react-router-dom'
import store from '../store';

export function withUser(InnerComponent) {
    return function OuterComponent(props) {
        const { userInfo } = store.getState();
        // return React.createElement(InnerComponent,{
        //     ...props,
        //     user:userInfo
        // })
        return <InnerComponent {...props} user={userInfo}></InnerComponent>
    }
}

// export function withStore(InnerComponent){
//     return function OuterComponent(props){
//         const state = store.getState();
//         return <InnerComponent {...props} {...state}></InnerComponent>
//     }
// }
export function withStore(mapStateToProps) {
    return function (InnerComponent) {
        return function OuterComponent(props) {

            let [userState, setUserState] = useState({})
            useEffect(() => {
                const state = store.getState();
                let newUserState
                try {
                    newUserState = mapStateToProps(state)
                } catch (err) {
                    newUserState = {}
                }

                setUserState(newUserState)

                // 监听redux数据修改
                store.subscribe(() => {
                    const state = store.getState();
                    let newUserState
                    try {
                        newUserState = mapStateToProps(state)
                    } catch (err) {
                        newUserState = {}
                    }

                    setUserState(newUserState)
                })

            }, [])

            return <InnerComponent {...props} {...userState}></InnerComponent>
        }
    }
}

/**
 * 用户登录才能访问组件
 * @param {Component} InnerComponent 
 * @returns 
 */
export function withLogin(InnerComponent) {
    return function WrapperComponent(props) {
        const { userInfo } = store.getState()
        const isLogin = useMemo(() => !!userInfo.Authorization, [userInfo])

        // 用户访问目标页面
        const { pathname: targetUrl } = useLocation()

        return isLogin ?
            <InnerComponent {...props} />
            :
            <Navigate to={"/login?target=" + targetUrl} />
    }
}